<template>
  <a-modal
    title="修改退货申请信息"
    :width="1488"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <div class="title">退货申请信息
        <a-button type="primary" style="margin-left: 20px;"  @click="handleAddApplyItem()">新增商品</a-button>
      </div>
      <a-table
        style="margin-bottom: 24px"
        rowKey="id"
        bordered
        :scroll="{ x: 800 }"
        :columns="returnGoodsColumns"
        :pagination="false"
        :dataSource="returnOrderEditColumns2" >
        <div slot="returnFileList" slot-scope="returnFileList, row">
          <template  v-for="(file, index) in returnFileList" >
            <a :href="file.url" target="_blank">{{ file.name }}</a>
          </template>
        </div>

        <span slot="action" slot-scope="text, record">
            <a-popconfirm title="确定删除吗?" style="padding-left: 10px;" placement="topLeft"
                          v-has="'order:cancel'" @confirm="() => handleDelete(record)">
                  <a>删除</a>
                </a-popconfirm>
          <a style="padding-left: 10px;" @click="addItemByItemId(record)">新增批次号</a>
        </span>
      </a-table>

      <div class="title">批次信息</div>
      <a-table
        size="middle"
        bordered
        :columns="goodsColumns"
        :dataSource="returnOrderEditColumns"
        :scroll="{ y: 440 }"
        :pagination="false"
        :loading="loading"
      >
        <div slot="returnUnitCountNotUnit" slot-scope="returnUnitCountNotUnit, row">
          <a-input-number
            id="inputNumber1"
            :value="returnUnitCountNotUnit"
            :min="0"
            @change="onChangeUnit($event, row)"
            :precision="0"
          />
        </div>
        <div slot="returnSkuUnitCountNotUnit" slot-scope="returnSkuUnitCountNotUnit, row">
          <a-input-number
            id="inputNumber2"
            :precision="0"
            :value="returnSkuUnitCountNotUnit"
            :min="0"
            @change="onChangeSkuUnit($event, row)"
          />
        </div>
        <div slot="batchNo" slot-scope="batchNo, row">
          <a-input-number
            id="inputNumber3"
            :precision="0"
            :value="batchNo"
            :min="0"
            style="width:150px"
            @change="onChangeBatchNo($event, row)"
          />
        </div>

        <span slot="updateAction" slot-scope="text, record">
               <a-popconfirm title="确定删除吗?" style="padding-left: 10px;" placement="topLeft"
                             v-has="'order:cancel'" @confirm="() => deleteApplyBatchItem(record)">
                  <a>删除</a>
                </a-popconfirm>
        </span>
      </a-table>

      <orderReturnProduct ref="OrderReturnProduct" @ok="modalFormOk" @refreshApplyItem="refreshApplyItem"/>

    </a-spin>
  </a-modal>
</template>

<script>
import pick from "lodash.pick";
import {httpAction, postAction} from "@/api/manage";
import {getAction} from "@/api/manage";
import OrderReturnProduct from '../../pms/modules/OrderReturnProduct'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {mergeSameProducts} from '@/utils/util'

export default {
  name: "UpdateOrderReturnApply",
  mixins: [JeecgListMixin],
  components: {
    OrderReturnProduct
  },

  data() {
    return {
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      approveStatus: 5,
      record: {},
      storeId: '',
      applyId: 0,
      instructionList: [],
      form: this.$form.createForm(this),
      validatorRules: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 13},
      },
      type: 1,
      returnOrderEditColumns: [],
      returnOrderEditColumns2: [],
      showTable: false,
      goodsColumns: [
        {
          title: "商品名称",
          key: "productName",
          dataIndex: "productName",
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {},
            };
            if (row.showName) {
              obj.attrs.rowSpan = row.rowSpan;
            } else if(row.hideName){
              obj.attrs.rowSpan = 0;
            } 
           
            return obj;
          },
        },
        {
          title: "批次号",
          key: "batchNo",
          dataIndex: "batchNo",
          scopedSlots: {customRender: "batchNo"},
        },
        {
          title: "申请数量（整箱）",
          key: "returnSkuUnitCountNotUnit",
          dataIndex: "returnSkuUnitCountNotUnit",
          scopedSlots: {customRender: "returnSkuUnitCountNotUnit"},
        },
        {
          title: "申请数量（零散）",
          key: "returnUnitCountNotUnit",
          dataIndex: "returnUnitCountNotUnit",
          scopedSlots: {customRender: "returnUnitCountNotUnit"},
        },
        {
          title: '操作',
          dataIndex: 'updateAction',
          width: 120,
          align: "center",
          // fixed: 'right',
          scopedSlots: {customRender: 'updateAction'},
        }
      ],
      returnGoodsColumns: [
        {
          title: '商品名称',
          key: 'productName',
          width: 150,
          dataIndex: 'productName'
        },
        {
          title: '物料编码',
          key: 'productSkuCode',
          width: 140,
          dataIndex: 'productSkuCode'
        },

        {
          title: '箱规',
          key: 'productSpecUnit',
          width: 100,
          dataIndex: 'productSpecUnit'
        },
        {
          title: '单价',
          key: 'unitPrice',
          width: 80,
          dataIndex: 'unitPrice'
        },
        {
          title: '箱装价',
          key: 'skuUnitPrice',
          width: 100,
          dataIndex: 'skuUnitPrice'
        },
        {
          title: '申请数量(整箱)',
          key: 'returnSkuUnitCount',
          width: 130,
          dataIndex: 'returnSkuUnitCount'
        },
        {
          title: '申请数量(零散)',
          key: 'returnUnitCount',
          width: 130,
          dataIndex: 'returnUnitCount'
        },
        {
          title: '数量小计',
          key: 'minUnitQuantityCount',
          width: 90,
          dataIndex: 'minUnitQuantityCount'
        },
        {
          title: '小计金额',
          key: 'totalAmount',
          width: 100,
          dataIndex: 'totalAmount'
        },
        {
          title: '申请原因',
          key: 'reason',
          width: 140,
          dataIndex: 'reason'
        },
        {
          title: '申请凭证',
          key: 'returnFileList',
          width: 140,
          dataIndex: 'returnFileList',
          scopedSlots: {customRender: "returnFileList"},
        },
        {
          title: '操作',
          dataIndex: 'action',
          // align: "center",
          // fixed: 'right',
          width: 160,

          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/returns/omsOrderReturnApply/list",
        returnOrderItem: "/returns/omsOrderReturnItem/returnOrderItem",
        returnBatchOrderItem: "/returns/omsOrderReturnItemBatch/returnBatchOrderItem",
        deleteApplyItem: "/returns/omsOrderReturnItem/deleteItemById",
        deleteApplyBatchItem: "/returns/omsOrderReturnItemBatch/deleteItemById",
        addItemByItemId: "/returns/omsOrderReturnItemBatch/addItemByItemId",
        updateBatchItem: "/returns/omsOrderReturnItemBatch/updateBatchItem",
      },
      loading: false,
    };
  },
  mounted(){
        // this.doShowTable()
  },
  computed: {},
  watch:{
    // visible(newV,oldV)  {
    //   console.log('newV', newV,oldV, this)
    //   if(newV) {
    //     this.doShowTable()
    //   } else {
    //     this.showTable = false;
    //   }
    // }
  },
  methods: {
    doShowTable() {
      setTimeout(() => {
        this.showTable = true;
      }, 400)
    },
    show(record) {
      this.record = record;
      this.instructionList = [];
      this.storeId = record.storeId;
      this.visible = true;

      this.model = Object.assign({}, record);
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, "channelFlag", 'note', "reason"));
      });
      if (record != {} && record.returnCertificate != null && record.returnCertificate.length > 0) {
        this.instructionList = eval(record.returnCertificate);
      }
      this.applyId = record.id;
      if (this.applyId) {
        this.loadGoodsData();
        this.loadReturnBatchData();
      }
    },
    refreshApplyItem() {
      this.loadGoodsData();
    },
    loadGoodsData() {
      var params = {applyId: this.applyId};
      this.loading = true;
      getAction(this.url.returnOrderItem, params).then((res) => {
        if (res.success) {
          console.log(1111111)
          this.returnOrderEditColumns2 = res.result;
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    loadReturnBatchData() {
      var params = {applyId: this.applyId};
      this.loading = true;
      getAction(this.url.returnBatchOrderItem, params).then((res) => {
        if (res.success) {
          
          this.returnOrderEditColumns = mergeSameProducts(res.result)
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    close() {
      this.form.resetFields();
      this.$emit("close");
      this.visible = false;
    },
    handleSubmit() {
      this.confirmLoading = true;
      let itemList = [];
      this.returnOrderEditColumns.forEach((row) => {
        const {returnUnitCountNotUnit, returnSkuUnitCountNotUnit, id, productId, batchNo} = row;
        itemList.push({
          returnUnitCountNotUnit,
          returnSkuUnitCountNotUnit,
          id,
          productId,
          batchNo
        });
      });
      let formData = {
        id: this.applyId,
        itemList,
      };
      this.form.validateFields((err, values) => {
        if (!err) {
          postAction(this.url.updateBatchItem, formData)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                this.$emit("ok");
                this.close();
              } else {
                this.$message.warning(res.message);
              }
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        }
      });
      this.confirmLoading = false;
    },
    handleCancel() {
      this.close();
    },
    handleWarehouseFlag(e) {
      this.model.channelFlag = e;
    },
    onChangeSkuUnit(event, row) {

      row.returnSkuUnitCountNotUnit = event;
    },
    onChangeUnit(event, row) {

      row.returnUnitCountNotUnit = event;
    },
    onChangeBatchNo(event, row) {

      row.batchNo = event;
    },
    handleDelete(record) {
      let url = this.url.deleteApplyItem + "/" + record.id
      getAction(url, {})
        .then((res) => {
          if (res.success) {
            this.loadGoodsData();
            this.loadReturnBatchData();
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    deleteApplyBatchItem(record) {
      let url = this.url.deleteApplyBatchItem + "/" + record.id
      getAction(url, {})
        .then((res) => {
          if (res.success) {
            this.loadReturnBatchData();
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    addItemByItemId(record) {
      let url = this.url.addItemByItemId + "/" + record.id
      getAction(url, {})
        .then((res) => {
          if (res.success) {
            this.loadReturnBatchData();
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    handleAddApplyItem() {
      this.$refs.OrderReturnProduct.show(this.storeId, this.applyId);
    }
  },
};
</script>
<style>

.title {
  margin-bottom: 10px;
  font-weight: bold;
  line-height: 1.5;
}
</style>